# -*- coding: utf-8 -*-

import threading


class Singleton(object):
    def __new__(cls, *args, **kw):
        if not hasattr(cls, '_instance'):
            orig = super(Singleton, cls)
            cls._instance = orig.__new__(cls, *args, **kw)
        return cls._instance


# class Singleton(type):
#     _instances = {}
#
#     def __call__(cls, *args, **kwargs):
#         if cls not in cls._instances:
#             cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
#         return cls._instances[cls]

# class Singleton(type):
#     _instance = None # 此处可改为_instances = {}字典实现
#
#     def __call__(cls,*arg,**kwarg):
#         if not cls._instance: # 条件相应得改为 not cls in _instances
#             cls._instance = cls.__new__(cls,*arg,**kwarg)
#             # 若instances为字典,则_instances[cls] = cls.__new__(cls,*arg,**kwarg)
#         return cls._instance


# class Singleton(type):
#     _instance_lock = threading.Lock()
#
#     def __call__(cls, *args, **kwargs):
#         if not hasattr(cls, "_instance"):
#             with Singleton._instance_lock:
#                 if not hasattr(cls, "_instance"):
#                     # obj = cls.__new__(cls, *args, **kwargs)
#                     # cls._instance = cls.__init__(obj, *args, **kwargs)
#                     cls._instance = super(Singleton, cls).__call__(*args, **kwargs)
#         return cls._instance


# def Singleton(cls):
#     # instance作为字典变量写在外部,可以保证该装饰器的重用性
#     _instances = {}
#
#     def get_instance(*arg,**kwarg):
#         if cls not in _instances:
#             _instances[cls] = cls(*arg,**kwarg)
#         return _instances[cls]
#     return get_instance


